using Life.UI.MVC.View;
using UnityEngine;
using ControllerTypeValue = System.Int32;

namespace Life.UI.MVC.Controller
{
    /// <summary>
    /// UI控制器基类 用于处理UI的数据更新、视图激活、视图隐藏等操作
    /// </summary>
    public abstract class ControllerBase : MonoBehaviour
    {
#if !MVCUI_CUSTOM_ENABLED
        [UnityEngine.Serialization.FormerlySerializedAs("modelToken")]
        [Header("UI关注的ModelToken")]
        //[SerializeField] protected ControllerType controllerType;
        [SerializeField][ControllerTypeSelect] protected ControllerTypeValue controllerType;
#endif
        [SerializeField] protected ViewBase _view;
        [SerializeField][Range(0,LayerRoot.MaxLayerCount - 1)] protected int _uiLayer;
        [SerializeField][Range(0,LayerRoot.MaxOrderCount - 1)] protected int _uiOrder;
        
        /// <summary>
        /// 当前UI所在组
        /// </summary>
        public int UILayer => _uiLayer;
        /// <summary>
        /// 当前UI所在组的顺序
        /// </summary>
        public int UiOrder => _uiOrder;
#if !MVCUI_CUSTOM_ENABLED
        public ControllerTypeValue TargetControllerType => controllerType;
        #else
        public ControllerTypeValue TargetControllerType => GetControllerType();
        protected abstract int GetControllerType();
#endif
        
        public bool ViewState => _view.gameObject.activeSelf;

        protected object HideCacheObj;

        private void Awake()
        {
            HideCacheObj = null;
            _view.gameObject.SetActive(false);
            OnAwake(UIManager.AddController(this));
        }

        /// <summary>
        /// 父类的Awake执行完成后调用
        /// </summary>
        /// <param name="awakeCompleted">标志着当前Controller添加至UIManager是否完成</param>
        protected virtual void OnAwake(bool awakeCompleted)
        {
            
        }
        /// <summary>
        /// 在视图隐藏后调用
        /// </summary>
        protected virtual void OnViewHide()
        {
            
        }
        
        /// <summary>
        /// 在视图激活后调用
        /// </summary>
        protected virtual void OnViewActive()
        {
            
        }

        /// <summary>
        /// 更新视图
        /// </summary>
        /// <param name="model"></param>
        public void UpdateView(Life.UI.MVC.Model.ModelBase model)
        {
            if (model.Token == TargetControllerType)
            {
                if (model is Life.UI.MVC.Model.StateModel { TransferTag: false } stateModel)//判断是否为StateModel
                {
                    if (stateModel.Enable)
                    {
                        ActivateView();
                    }
                    else
                    {
                        DeactivateView(stateModel.ClearView);
                    }
                    return;
                }
                
                //TransferTag==true的StateModel和其他Model交给子类处理
                if (OnModelUpdate(model))
                {
                    if (model.ActivateNow && !ViewState)
                    {
                        ActivateView();
                    }
                }
                else
                {
#if !MVCUI_CUSTOM_ENABLED
                        ControllerType.ParseToName(model.Token, out var typeName);
                        Debug.LogError($"Dev: {name} UpdateView Failed, ModelToken: {typeName} not be supported.");
#else
                    Debug.LogError($"Dev: {name} UpdateView Failed, ModelToken: {model.GetType().Name} {UIManager.ConvertTokenToString(model.Token)} not be supported.");
#endif
                }
            }
            else
            {
#if !MVCUI_CUSTOM_ENABLED
                ControllerType.ParseToName(model.Token, out var typeName);
                Debug.LogError($"Dev: {name} UpdateView Failed, ModelToken: {typeName} not match.");
#else
                Debug.LogError($"Dev: {name} UpdateView Failed, ModelToken: {model.GetType().Name} & {name}.TargetControllerType not match.");
#endif
            }
        }

        /// <summary>
        /// 获取视图控制器的缓存
        /// </summary>
        /// <returns></returns>
        public object ControllerCache()
        {
            return HideCacheObj;
        }

        /// <summary>
        /// 隐藏UI
        /// </summary>
        protected void HideView()
        {
            UIManager.HideView(TargetControllerType);
        }

        private void ClearView()
        {
            _view.OnClear();
        }
        /// <summary>
        /// 用于激活视图
        /// </summary>
        private void ActivateView()
        {
            HideCacheObj = null;
            _view.SetActive(true);
            OnViewActive();
        }
        /// <summary>
        /// 用于隐藏视图
        /// </summary>
        /// <param name="clear"></param>
        private void DeactivateView(bool clear = true)
        {
            if (clear)
            {
                _view.OnClear();
            }
            _view.SetActive(false);
            OnViewHide();
        }
        
        /// <summary>
        /// 视图数据更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns>如果已处理该数据，请返回true</returns>
        protected abstract bool OnModelUpdate(Life.UI.MVC.Model.ModelBase model);
        
        #if UNITY_EDITOR
        
        #if ODIN_INSPECTOR
        [Sirenix.OdinInspector.BoxGroup("Run Test On Playing")]
        [Sirenix.OdinInspector.Button]
        private void SimpleShow()
        {
            if(Application.isPlaying)
                UIManager.ShowView((int)TargetControllerType);
        }
        [Sirenix.OdinInspector.BoxGroup("Run Test On Playing")]
        [Sirenix.OdinInspector.Button]
        private void SimpleHide()
        {
            if(Application.isPlaying)
                UIManager.HideView((int)TargetControllerType);
        }
        #endif
        
        private void Reset()
        { 
            try
            {
#if !MVCUI_CUSTOM_ENABLED
                string enumString = GetType().Name.Replace("View", "");
                ControllerType.ParseToValue(enumString, out controllerType);         
#endif
            }
            catch
            {
                // ignored
            }
        }
        #endif
    }
}
